package com.troila.cloud.simplify.filter;

import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.troila.cloud.simplify.model.ExpireableMap;
import com.troila.cloud.simplify.model.WechatUserAccount;
import com.troila.cloud.simplify.service.WechatUserAccountService;

import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@Component
public class WechatInterceptor implements HandlerInterceptor {
	private static final Logger LOGGER = LoggerFactory.getLogger(WechatInterceptor.class);
	
	@Autowired
	private WechatUserAccountService wechatUserAccountService;
	
	@Autowired
	private WxMpService wechat;
	
	@Value("${question.domain}")
	private String domain;
	
//	@Autowired
	private static ExpireableMap<String, Object> code2FollowerCache = new ExpireableMap<>(32, 1000 * 60 * 60);

//	public WechatInterceptor(Site site) {
//		this.site = site;
//	}

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest req, HttpServletResponse arg1, Object arg2, ModelAndView model)
			throws Exception {
		if (model != null) {
//			model.getModelMap().addAttribute("site", site);
			
			StringBuffer urlBuilder = new StringBuffer();
			if(req.getRequestURI().indexOf("front/page") >= 0) {
				urlBuilder.append(domain+"/smallQuestion/index");
			}else {
				urlBuilder.append(domain+req.getRequestURI());
			}
			String query = req.getQueryString();
			if(StringUtils.isNotBlank(query)) {
				urlBuilder.append("?").append(query);
			}
			WxJsapiSignature signature = wechat.createJsapiSignature(urlBuilder.toString());
			System.out.println("signature:"+signature.getSignature());
			System.out.println("time:"+signature.getTimestamp());
			System.out.println("appid:"+signature.getAppId());
			System.out.println("url:"+signature.getUrl());
			model.getModelMap().addAttribute("wx", signature);
		}
	}

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object arg2) throws Exception {
		
		/*String wxid = req.getParameter("wxid");
		if (StringUtils.isNoneBlank(wxid)) {
			WechatUserAccount wechatUserAccount = wechatUserAccountService.findByWxid(wxid);
			req.getSession().setAttribute("wechatUserAccount", wechatUserAccount);
			return true;
		}

		*//**
		 * 为了避免 code 重用的问题， 将每一个使用过的code 缓存起来
		 *//*
		String code = req.getParameter("code");
		if (StringUtils.isNoneBlank(code)) {
			LOGGER.debug("wx code {}", code);
			if(code2FollowerCache.containsKey(code)) {
				LOGGER.debug("wx code cached {}, followered is retrieved from cache", code);
				req.getSession().setAttribute("follower", code2FollowerCache.get(code));
				return true;
			}
			
			WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wechat.oauth2getAccessToken(code);
			WxMpUser wxMpUser = wechat.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
			WechatUserAccount wechatUserAccount = wechatUserAccountService.findByWxid(wxMpUser.getOpenId());
//			Timestamp now = new Timestamp(System.currentTimeMillis());
			if(wechatUserAccount == null) {
				wechatUserAccount = new WechatUserAccount();
				wechatUserAccount.setGmtCreate(new Date());
				wechatUserAccount.setWxid(wxMpUser.getOpenId());
			} 
			wechatUserAccount.setNickname(wxMpUser.getNickname());
			wechatUserAccount.setAvatar(wxMpUser.getHeadImgUrl());
			wechatUserAccount.setSex(wxMpUser.getSexId());
			wechatUserAccount.setGmtModify(new Date());
			LOGGER.debug("wx code {}, followered is put to cache", code);
			code2FollowerCache.put(code, wechatUserAccount);
			req.getSession().setAttribute("wechatUserAccount", wechatUserAccount);
			wechatUserAccount = wechatUserAccountService.save(wechatUserAccount);
			return true;
		}*/
		return true;
	}

}
